import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: "/login",
    name: 'login',
    component: () => import("../views/login.vue")
  },
  {
    path: "/",
    name: 'index',
    component: () => import("../views/index.vue")
  },
  {
    path: "/cart",
    name: 'cart',
    component: () => import("../views/gouwuche.vue")
  },
  {
    path: '/detail',
    name: 'detail',
    component: () => import('../views/detail.vue')
  },
  {
    path: '/category',
    name: 'category',
    component: () => import('../views/category.vue')
  },
  {
    path: '/profile',
    name: 'profile',
    component: () => import('../views/profile.vue')
  }
]

const router = new VueRouter({
  routes
})

// 路由前置守卫
router.beforeEach((to, from, next) => {
  // to 目标页面 from 当前页面信息 next() 拦截/放行
  // 登录拦截  判断登录信息(浏览器缓存是否有userInfo)
  if (to.path === '/') {
    next()
    return false
  }
  if (!localStorage.getItem('userInfo') && to.path !== '/login') {
    next('/login')
  } else {
    next()
  }
})

export default router